import React, { useEffect, useRef } from 'react';
import { View, TouchableOpacity } from 'react-native';

import { DropdownMenuOptions, useDropdownMenu } from './context';

interface AnimatedDropdownMenuProps extends React.PropsWithChildren {
  options: DropdownMenuOptions[];
}

const DropdownMenu = ({ children, options }: AnimatedDropdownMenuProps) => {
  const viewRef = useRef<View>(null);
  const { setOpen, setOptions, setPosition } = useDropdownMenu();

  const toggleDropdown = () => {
    setOpen((prev) => !prev);
  };
  // 选项变化时更新
  useEffect(() => {
    setOptions(options);
  }, [options, setOptions]);

  const handleLayout = () => {
    viewRef.current?.measure((_x, _y, _width, _height, pageX, pageY) => {
      setPosition({ x: pageX, y: pageY });
    });
  };

  return (
    <View ref={viewRef} onLayout={handleLayout}>
      <TouchableOpacity onPress={toggleDropdown}>{children}</TouchableOpacity>
    </View>
  );
};

export default DropdownMenu;
